<template>
  <div class="cart-container">
    <!-- 添加返回按钮 -->
    <div class="header-with-back">
      <div class="back-button" @click="handleBack">
        <svg viewBox="0 0 24 24" width="24" height="24">
          <path fill="currentColor" d="M15.41 16.59L10.83 12l4.58-4.59L14 6l-6 6 6 6 1.41-1.41z"/>
        </svg>
      </div>
      <h3 class="page-title">购物车</h3>
    </div>
    <!-- 购物车列表 -->
    <div class="cart-list">
      <div v-if="items.length === 0" class="empty-cart">
        <el-empty description="购物车空空如也" />
        <el-button type="primary" @click="goShopping">去逛逛</el-button>
      </div>

      <el-card v-for="item in items" :key="item.id" class="cart-item">
        <div class="item-content">
          <el-checkbox v-model="item.selected" class="item-checkbox" />
          <el-image
              :src="item.product.image || 'https://img.yzcdn.cn/vant/ipad.jpeg'"
              fit="cover"
              class="product-image"
          />
          <div class="product-info">
            <h4 class="product-title">{{ item.product.title }}</h4>
            <p class="product-desc">{{ item.product.description }}</p>
            <div class="bottom-controls">
              <span class="price">¥{{ item.product.price.toFixed(2) }}</span>
              <el-input-number
                  v-model="item.quantity"
                  :min="1"
                  :max="99"
                  @change="updateQuantity(item)"
                  size="small"
                  class="quantity-input"
              />
            </div>
          </div>
          <el-button
              type="danger"
              icon="Delete"
              circle
              plain
              @click="removeItem(item.id)"
              class="delete-btn"
          />
        </div>
      </el-card>
    </div>

    <!-- 结算栏 -->
    <div v-if="items.length > 0" class="checkout-bar">
      <div class="select-all">
        <el-checkbox v-model="selectAll" class="select-all-checkbox">
          全选
        </el-checkbox>
        <div class="total-section">
          <span class="total-price">
            合计：<span class="amount">¥{{ totalPrice.toFixed(2) }}</span>
          </span>
          <span class="item-count">({{ selectedCount }}件)</span>
        </div>
      </div>
      <el-button
          type="primary"
          round
          :disabled="selectedCount === 0"
          @click="showCheckoutDialog"
          class="checkout-btn"
      >
        结算
      </el-button>
    </div>

    <!-- 结算对话框 -->
    <el-dialog
        v-model="checkoutDialogVisible"
        title="确认订单信息"
        width="90%"
        :before-close="handleClose"
    >
      <el-form :model="checkoutForm" label-width="80px">
        <el-form-item label="收货地址">
          <el-input v-model="checkoutForm.address" placeholder="请输入收货地址" />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="checkoutForm.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="订单备注">
          <el-input
              v-model="checkoutForm.remark"
              type="textarea"
              :rows="2"
              placeholder="请输入订单备注（选填）"
          />
        </el-form-item>
        <el-form-item label="订单总价">
          <span class="dialog-price">¥{{ totalPrice.toFixed(2) }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="checkoutDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCheckout">确认支付</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ref, computed, onMounted, onBeforeUnmount, inject} from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import axios from 'axios';

const router = useRouter();
const user = ref(JSON.parse(localStorage.getItem('user') || 'null'))
const loading = ref(false);
const allItemsLoaded = ref(false);
const currentPage = ref(1);
const checkoutDialogVisible = ref(false);


interface CartItem {
  id: number;
  product: {
    id: number;
    title: string;
    description: string;
    price: number;
    image?: string;
  };
  quantity: number;
  selected: boolean;
  amount: number;
  status: number;
}

const items = ref<CartItem[]>([]);

// 添加返回方法
const handleBack = () => {
  router.go(-1); // 返回上一页
};

// 结算表单
const checkoutForm = ref({
  address: '',
  contactPhone: '',
  remark: ''
});

// 显示结算对话框
const showCheckoutDialog = () => {
  const selectedItems = items.value.filter(item => item.selected);
  if (selectedItems.length === 0) {
    ElMessage.warning('请选择要结算的商品');
    return;
  }
  checkoutDialogVisible.value = true;
};

// 确认结算
const confirmCheckout = async () => {
  try {
    const selectedItems = items.value.filter(item => item.selected);

    // 验证表单
    if (!checkoutForm.value.address) {
      ElMessage.warning('请输入收货地址');
      return;
    }
    if (!checkoutForm.value.contactPhone) {
      ElMessage.warning('请输入联系电话');
      return;
    }

    // 调用API更新订单状态和地址信息
    const updatePromises = selectedItems.map(item =>
        axios.post('/backend/order/update', {
          id: item.id,
          status: 1, // 已支付
          address: checkoutForm.value.address,
          contactPhone: checkoutForm.value.contactPhone,
          remark: checkoutForm.value.remark
        })
    );

    await Promise.all(updatePromises);

    // 从购物车移除已支付的订单
    items.value = items.value.filter(item => !item.selected);
    checkoutDialogVisible.value = false;
    ElMessage.success('支付成功');

  } catch (error) {
    ElMessage.error('支付失败');
    console.error(error);
  }
};

// 关闭对话框前的处理
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('确定要取消支付吗？')
      .then(() => {
        done();
      })
      .catch(() => {});
};

// 获取购物车数据（带隐形分页）
const fetchCartItems = async () => {
  if (loading.value || allItemsLoaded.value) return;

  loading.value = true;
  try {
    const response = await axios.get('/backend/order/query', {
      params: {
        buyerId: user.value.id,
        status: 0,
        pageNum: currentPage.value,
        pageSize: 10 // 每页10条
      }
    });

    if (response.data.code === 200) {
      const newItems = response.data.data.list.map((order: any) => ({
        id: order.id,
        product: {
          id: order.product.id,
          title: order.product.title,
          description: order.product.description,
          price: order.product.price,
          image: order.product.images?.split(',')[0]
        },
        quantity: Math.round(order.amount / order.product.price),
        selected: false,
        amount: order.amount,
        status: order.status
      }));

      items.value = [...items.value, ...newItems];

      // 判断是否已加载全部数据
      if (response.data.data.list.length < 10 ||
          currentPage.value >= response.data.data.totalPages) {
        allItemsLoaded.value = true;
      } else {
        currentPage.value++;
      }
    }
  } catch (error) {
    ElMessage.error('获取购物车失败');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 更新商品数量（实际更新总金额）
const updateQuantity = async (item: CartItem) => {
  try {
    // 计算新总金额
    const newAmount = item.product.price * item.quantity;

    // 更新本地数据
    item.amount = newAmount;

    // 调用API更新订单金额
    await axios.post('/backend/order/update', {
      id: item.id,
      amount: newAmount
    });

    ElMessage.success('更新成功');
  } catch (error) {
    ElMessage.error('更新数量失败');
    console.error(error);
  }
};

// 删除商品
const removeItem = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const response = await axios.get(`/backend/order/delete?id=${id}`);

    if (response.data.code === 200) {
      items.value = items.value.filter(item => item.id !== id);
      ElMessage.success('删除成功');
    } else {
      ElMessage.error(response.data.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
      console.error(error);
    }
  }
};

// 全选/取消全选
const selectAll = computed({
  get: () => {
    return items.value.length > 0 && items.value.every(item => item.selected)
  },
  set: (value) => {
    items.value.forEach(item => {
      item.selected = value
    })
  }
})

// 计算总价
const totalPrice = computed(() => {
  return items.value
      .filter(item => item.selected)
      .reduce((sum, item) => sum + item.product.price * item.quantity, 0);
});

// 计算选中数量
const selectedCount = computed(() => {
  return items.value.filter(item => item.selected).length;
});

// 去购物
const goShopping = () => {
  router.push('/products');
};

// 初始化滚动监听
onMounted(() => {
  fetchCartItems();
  const cartList = document.querySelector('.cart-list');
  if (cartList) {
    cartList.addEventListener('scroll', handleScroll);
  }
});
// 滚动加载更多
const handleScroll = () => {
  const cartList = document.querySelector('.cart-list');
  if (cartList &&
      cartList.scrollTop + cartList.clientHeight >= cartList.scrollHeight - 100 &&
      !loading.value) {
    fetchCartItems();
  }
};
// 移除滚动监听
onBeforeUnmount(() => {
  const cartList = document.querySelector('.cart-list');
  if (cartList) {
    cartList.removeEventListener('scroll', handleScroll);
  }
});
</script>

<style scoped>
.cart-container {
  padding: 10px;
  height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
}

.empty-cart {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 60vh;
  gap: 20px;
}

.cart-item {
  margin-bottom: 10px;
  padding: 8px;
}

.item-content {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  position: relative;
}

.item-checkbox {
  margin-right: 5px;
}

.product-image {
  width: 70px;
  height: 70px;
  border-radius: 4px;
  flex-shrink: 0;
}

.product-info {
  flex: 1;
  min-width: 0; /* 防止内容溢出 */
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.product-title {
  margin: 0;
  font-size: 14px;
  font-weight: 500;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 1.4;
}

.product-desc {
  margin: 0;
  font-size: 12px;
  color: #999;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.bottom-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 6px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 14px;
}

.quantity-input {
  width: 100px;
}

.delete-btn {
  position: absolute;
  right: 0;
  top: 0;
  transform: scale(0.8);
}

.checkout-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 8px 12px;
  background: white;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.select-all {
  display: flex;
  align-items: center;
  gap: 8px;
}

.select-all-checkbox {
  margin-right: 5px;
}

.total-section {
  display: flex;
  flex-direction: column;
  margin-left: 8px;
}

.total-price {
  font-size: 14px;
  font-weight: bold;
}

.amount {
  color: #f56c6c;
  font-size: 16px;
}

.item-count {
  font-size: 12px;
  color: #999;
}

.checkout-btn {
  padding: 10px 20px;
  font-size: 14px;
}

.cart-list {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 70px;
  scroll-behavior: smooth;
}

.dialog-price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 18px;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .product-image {
    width: 60px;
    height: 60px;
  }

  .product-title {
    font-size: 13px;
  }

  .product-desc {
    font-size: 11px;
  }

  .price {
    font-size: 13px;
  }

  .quantity-input {
    width: 90px;
  }

  .checkout-bar {
    padding: 6px 10px;
  }

  .checkout-btn {
    padding: 8px 16px;
    font-size: 13px;
  }

  .total-price {
    font-size: 13px;
  }

  .amount {
    font-size: 15px;
  }
}

@media (max-width: 360px) {
  .product-image {
    width: 50px;
    height: 50px;
  }

  .item-content {
    gap: 6px;
  }

  .quantity-input {
    width: 80px;
  }
}
</style>